package com.example.myapplication.util;

import android.os.Build;
import androidx.annotation.RequiresApi;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 需要在成员变量上打上FiledOrder注解，才能正确使用
 */
public class TableUtils {
    public static ArrayList<ArrayList<String>> convertObjectListToStringLists(List objectList, boolean isAddOrder, String... headers) {
        ArrayList<ArrayList<String>> arrayLists = new ArrayList<>();
        ArrayList<String> headerStrings = new ArrayList<>();
        if (isAddOrder) {
            headerStrings.add("序号");
        }
        headerStrings.addAll(Arrays.asList(headers));
        arrayLists.add(headerStrings);
        Field[] fields;
        if (objectList.size() > 0) {
            fields = objectList.get(0).getClass().getDeclaredFields();
            for (Field field : fields) {
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
            }
            Arrays.sort(fields, (f1, f2) -> {
                FieldOrder order1 = f1.getAnnotation(FieldOrder.class);
                FieldOrder order2 = f2.getAnnotation(FieldOrder.class);
                if (order1 != null && order2 != null) {
                    return order1.order() - order2.order();
                } else {
                    return 0;
                }
            });
        } else {
            return arrayLists;
        }
        int order = 1;
        for (Object o : objectList) {
            ArrayList<String> strings = new ArrayList<>();
            if (isAddOrder) {
                strings.add(order++ + "");
            }
            for (Field field : fields) {
                try {
                    Object filedObject = field.get(o);
                    if (filedObject != null) {
                        strings.add(filedObject.toString());
                    } else {
                        strings.add("null");
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            arrayLists.add(strings);
        }
        return arrayLists;
    }
}
